package com.iiixxxiii.pf.api.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
/**
 * 消费者模版
 *
 */
public class KafkaConsumerTemplate {
    private boolean runner = true;
    public KafkaConsumerTemplate(String servers,
                                 String keyDeserializer,
                                 String valueDeserializer,
                                 String group,
                                 String topic) {
        Properties props = new Properties();
        props.put("bootstrap.servers", servers);
        props.put("key.deserializer", keyDeserializer);
        props.put("value.deserializer", valueDeserializer);
        props.put("group.id", group);//不同ID 可以同时订阅消息
        /*
        props.put("enable.auto.commit", "false");
        props.put("auto.commit.interval.ms", "1000");
        props.put("session.timeout.ms", "30000");*/
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList(topic));//订阅TOPIC
        System.out.println("group.id:" + group);
        System.out.println("订阅TOPIC:" + topic);
        try {
            while (runner) {
            	//Duration.ofMillis(Long.MAX_VALUE)
                ConsumerRecords<String, String> records = consumer.poll( Duration.ofMillis(99999) );
              
                for (TopicPartition partition : records.partitions()) {
                    List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
                    for (ConsumerRecord<String, String> record : partitionRecords) {
                        //可以自定义Handler,处理对应的TOPIC消息(partitionRecords.key())
                        System.out.println( "消费: "+ record.offset() + ": " + record.value());
                    }
                    /*consumer.commitSync();//同步*/
                }
            }
        }catch (Exception e) {
			// TODO: handle exception
		    e.printStackTrace();
        } finally {
            consumer.close();
        }
    }
    public void setRunner(boolean runner) {
        this.runner = runner;
    }
}